package com.cxyd.modules.job.task.logicTask;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cxyd.common.constant.Constant;
import com.cxyd.common.constant.enums.wms.TaskStEnum;
import com.cxyd.common.exception.RootException;
import com.cxyd.common.utils.ApiResult;
import com.cxyd.common.utils.StringUtils;
import com.cxyd.modules.wms.dao.TaskDao;
import com.cxyd.modules.wms.dao.UrlMappingDao;
import com.cxyd.modules.wms.dto.PostWcsDTO;
import com.cxyd.modules.wms.entity.TaskEntity;
import com.cxyd.modules.wms.entity.UrlMappingEntity;
import com.cxyd.modules.wms.service.PostWcsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Component("post-wcs")
@Slf4j
public class PostWcsTask {

    private final RestTemplate restTemplate;
    private final PostWcsService postWcsService;
    private final UrlMappingDao urlMappingDao;
    private final TaskDao taskDao;
    //创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();

    public PostWcsTask(RestTemplate restTemplate, PostWcsService postWcsService, UrlMappingDao urlMappingDao, TaskDao taskDao) {
        this.restTemplate = restTemplate;
        this.postWcsService = postWcsService;
        this.urlMappingDao = urlMappingDao;
        this.taskDao = taskDao;
    }

    public void scanTask() {
        lock.lock();
        try {
            PostWcsDTO record = postWcsService.getOneRecord();
            Date date = new Date();

            if (record == null) {
//                log.warn("无任务");
                return;
            }

            if (StringUtils.isBlank(record.getRequestPk()) || StringUtils.isBlank(record.getContNo())) {
                return;
            }
            UrlMappingEntity urlMappingEntity = urlMappingDao.selectOne(new QueryWrapper<UrlMappingEntity>().eq("url_no", "WCS_URL"));
            if (ObjectUtils.isEmpty(urlMappingEntity) || StringUtils.isBlank(urlMappingEntity.getUrlAdr())) {
                throw new RootException("下发WCS设备URL不存在！");
            }
            ApiResult respond = restTemplate.postForObject(urlMappingEntity.getUrlAdr(), record, ApiResult.class);
            if (respond == null) {
                return;
            }
            /*发送成功则处理数据*/
            if (respond.getRequestPk().length() == 0) {
                return;
            }
            //构建map记录接收到的反馈信息
            final Map<String, Object> map = new HashMap<>();
            map.put("pk", respond.getRequestPk());
            map.put("code", respond.getCode());
            map.put("msg", respond.getMsg());
            postWcsService.updateByPk(map);

            //修改task(更新任务为初始的)
            taskDao.update(null, new UpdateWrapper<TaskEntity>()
                    .eq("cont_no", record.getContNo())
                    .eq("task_st", TaskStEnum.INITIAL.getCode())
                    .set("task_st", TaskStEnum.PROGRESS.getCode())
                    .set("updater", Constant.ClientCode.WMS.getId())
                    .set("update_date", date)
                    .set("comments", "WCS定时任务"));

        } catch (Exception e) {
            log.error("下发搬送指令异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();//释放锁
        }
    }
}
